package com.colis.quartz.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p> 描述：自定义线程池 </p>
 *
 * @author wlp
 * @version 1.0.0
 * @date 2022/1/13 15:43
 */
@Slf4j
@Configuration
public class ExecutorConfig {

    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        executor.setMaxPoolSize(128);
        executor.setKeepAliveSeconds(4);
        executor.setQueueCapacity(0);
        executor.setRejectedExecutionHandler((Runnable r, ThreadPoolExecutor exe) -> {
            // 利用BlockingQueue的特性，任务队列满时等待放入
            try {
                if (!exe.getQueue().offer(r, 30, TimeUnit.SECONDS)) {
                    log.error("Task offer failed after 30 sec");
                }
            } catch (InterruptedException e) {
                log.error("队列获取出错了！", e);
                Thread.currentThread().interrupt();
            }
        });
        return executor;
    }
}
